import React, { useContext, useEffect, useMemo, useState } from 'react';
import { Steps, Button, Spin, Space, message } from 'antd';
import { connect, history } from 'umi';

import UpdateStepsApply from './UpdateStepsApply';
import UpdateStepsPack from './UpdateStepsPack';
import UpdateStepsBaseInfo from './UpdateStepsBaseInfo';

import '../common/style.less';
import { useApplyUpdate } from '../common/useApplyUpdate';
import { useApplyStep } from '../common/useApplyStep';
import { ApplyUpdateContext } from '../common/ApplyContext';

import { getCompanyID, getInvoiceCode, getKeyRouter, getPosIDs, getTenantID, getUserDepID, getUserID } from '@/utils';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { WorkflowChedkRecord, WorkflowNoDefaultTable, WorkflowSwitchModal, WorkflowCheckModal, WorkflowHndTaskBtn } from '@/components/WorkflowCommonCopy';

import {
  CGZ_SQSTATE,
  DCG_SQSTATE,
  FSBG_STATE_QC,
  FSBG_STATE_SHZ,
  QC_SQSTATE,
  SHZ_SQSTATE,
  SQ_LX_businessCategory,
  SQ_businessCategory,
  SQ_flowBusinessType,
  SQ_orderType,
  SQ_requestController,
  ZF_SQSTATE,
  onMouseOut_ANTDBTN,
} from '../common/Format';
import { useContractsReducer } from '../common/ApplyReducer';
import { ILoadMapTypeAll } from '@/common';
import { addSourceDataServices, inspectChangeStateService, updatePlanStateServices } from '../services/UpdateService';
import { SHTG_CHECKSTATE, SHTH_CHECKSTATE, closeCurrent, procurementCodeCheck } from '../../Acommon';

import { SHZF_CHECKSTATE } from '../../Acommon/PurchaseState';
import { cancelModalRequest } from '../common/CancelModal/services';
import moment from 'moment';

const ApplyUpdateView: React.FC<Record<string, any>> = ({ locationProps, curRes }) => {
  /**
   * @type add & edit & view
   * @supplyWay 采购办法
   * @info 计划或申请信息
   * @source 来源入口
   * @step 步骤条的几步
   */
  const { type = 'view', supplyWay, info = {}, source, step = 0, isRefresh, returnPathName } = locationProps?.state || {};
  const { currentStep, changeStep, stepsItems, setCurrentStep } = useApplyStep({ step }); // 步骤条配置

  const { prefixCls, materialList, dataSource } = useContext(ApplyUpdateContext);
  const { dispatch, supplyTK, page, ProjectInfo } = useContractsReducer();

  const [successMaterials, setSuccessMaterials] = useState<Record<string, any>[]>([]); // 所有已经分包成功的标的集合
  const [finallyType, setFinallyType] = useState<string>('');
  const [isState, setIsState] = useState<boolean>(false);
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); // 撤销弹窗
  const [packData, setPackData] = useState<Record<string, any>[]>([]); // 包数据集合
  const [isCancellation, setIsCancellation] = useState(false); // 是否会触发释放物料接口
  const [isShowAuditRecord, setIsShowAuditRecord] = useState<boolean>(false); // 审批记录渲染控制
  const [inspectChangeState, setInspectChangeState] = useState(true); // 根据有没有变更申请，来控制提交按钮的展示
  const [isShowWorkflowCheck, setIsShowWorkflowCheck] = useState<Record<string, any>>({}); // 是否显示工作流弹窗

  const { applyInfo, submit, isShowState, change, ref, loading } = useApplyUpdate({
    currentStep,
    info,
    source,
    state: {
      supplyTK,
      page,
      successMaterials,
      setSuccessMaterials,
      ProjectInfo,
      dispatch,
    },
    isRefresh,
  });

  let { reloadInfoService } = change; // 解构方法

  // 修改计划状态,采购申请审批同意后-修改计划状态信息 [执行中]
  const { updatePlanStateRun } = updatePlanStateServices((res) => {
    if (res?.msgFlag) {
      message.success(res.msg);
      reloadInfoService();
    }
  });

  // 添加实施接口
  const { addSourceDataRun } = addSourceDataServices((res) => {
    if (res?.msgFlag) {
      message.success(res.msg);
      const params = {
        calibrateID: null,
        applyID: applyInfo?.id,
        state: `1`,
      };
      updatePlanStateRun(params); //更新计划状态
    }
  });

  // 作废接口
  const { cancelModalRun } = cancelModalRequest(
    (res: Record<string, any>) => {
      if (res && res?.msgFlag) {
        message.success(res?.msg);
      } else {
        message.error(res?.msg);
      }
    },
    'PUT',
    '/purchaseApplyController/cancelApply',
  );

  // 查询当前申请下是否有标包在走变更申请流程
  const { inspectChangeStateRun } = inspectChangeStateService((res) => {
    const { msgFlag, msg } = res;
    if (msgFlag) {
      setInspectChangeState(true);
    } else {
      setInspectChangeState(false);
      message?.warning(msg);
    }
  });

  // 设置页面标识 [edit | view | add]
  useEffect(() => {
    if (type == 'edit') {
      if (applyInfo?.id && applyInfo?.state == QC_SQSTATE() && !applyInfo?.checkState) {
        // 编辑
        setFinallyType('edit');
      } else if (applyInfo?.state == SHZ_SQSTATE() && applyInfo?.checkState == SHTH_CHECKSTATE()) {
        // 编辑
        setFinallyType('edit');
      } else {
        // 查看
        setFinallyType('view');
      }
    } else if (type == 'view') {
      setFinallyType('view');
      setCurrentStep(2);
    }
  }, [type, applyInfo]);

  // 监听状态添加实施
  useEffect(() => {
    /** 设置开关 - 添加实施的 */
    if (applyInfo?.state && applyInfo?.state != DCG_SQSTATE() && applyInfo?.checkState && applyInfo?.checkState != SHTG_CHECKSTATE()) {
      setIsState(true);
    }
    if (applyInfo?.state && applyInfo?.state == DCG_SQSTATE() && applyInfo?.checkState && applyInfo?.checkState == SHTG_CHECKSTATE()) {
      /** 判断开关，确保最后一个审批人是在采购申请审核中进入到页面 */
      if (isState) {
        let arr = [];
        arr = applyInfo?.mpurchasePacks.map((item: any) => {
          return {
            packID: item.id,
            // 这是添加实施（招标文件编制）的接口，实施（招标文件编制）需要用来开启流程
            businessType: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1004`, //流程类别
            workflowType: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1004`, //流程类型
            state: procurementCodeCheck(item?.procureReal)
              ? `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1010` //实施状态 待实施
              : `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1000`, //实施状态：待编制
            syncFinanceTime: procurementCodeCheck(item?.procureReal) ? moment(new Date()).format('YYYY-MM-DD HH:mm:ss') : null,
          };
        });
        const result = applyInfo?.mpurchasePacks?.find((item) => procurementCodeCheck(item?.procureReal));
        let reqBody: Record<string, any> = {
          applyID: applyInfo?.id,
          mpurchaseSourceList: arr,
          sourceCode: getInvoiceCode('SS'),
        };
        if (result) {
          reqBody.applyState = CGZ_SQSTATE();
        }
        addSourceDataRun({ ...reqBody });
      }
    }

    /** 判断是否是 审批中-审核退回-当前申请用户 后面要监听状态的变化进行作废后立即调用释放接口*/
    if (applyInfo?.state == SHZ_SQSTATE() && applyInfo?.checkState == SHTH_CHECKSTATE() && applyInfo?.applyerID == getUserID()) {
      setIsCancellation(true);
    }
  }, [applyInfo?.state, applyInfo?.checkState]);

  // 流程作废时，监听状态变化，作废完成后立即调用释放资源接口
  useEffect(() => {
    if (applyInfo?.state == ZF_SQSTATE() && applyInfo?.checkState == SHZF_CHECKSTATE()) {
      if (isCancellation) {
        let params = {
          cancelType: '100122101001',
          cancelReason: '1',
          cancelFlag: '0',
          versionNum: 0,
          state: ZF_SQSTATE(),
          id: applyInfo?.id,
          cancelerID: getUserID(),
          cancelPositionID: getPosIDs(),
          cancelDepartmentID: getUserDepID(),
          cancelCompanyID: getCompanyID(),
        };
        cancelModalRun(params);
      }
    }
  }, [isCancellation, applyInfo?.state, applyInfo?.checkState]);

  // 查询当前申请下是否有标包在走变更申请流程
  useEffect(() => {
    if (currentStep == 2 && applyInfo?.packs?.length) {
      inspectChangeStateRun({
        packIds: applyInfo?.packs?.map((i) => i.id).join(','),
        changeState: `${FSBG_STATE_QC()},${FSBG_STATE_SHZ()}`,
      });
    }
  }, [currentStep, applyInfo]);

  // 判断是否展示提交按钮
  const isShowSubmit = useMemo(() => {
    if (currentStep == 2) return false;
    if (finallyType == 'view') return false;
    if (currentStep == 0) {
      if (applyInfo?.id) {
        if (applyInfo?.state == QC_SQSTATE() && !applyInfo?.checkState && curRes?.['/purchaseApplyController/editApply']) {
          return true;
        }
        if (
          applyInfo?.state == SHZ_SQSTATE() &&
          applyInfo?.checkState == SHTH_CHECKSTATE() &&
          applyInfo?.applyerID == getUserID() &&
          applyInfo?.applyPositionID == getPosIDs() &&
          curRes?.['/purchaseApplyController/editApply']
        ) {
          return true;
        }
      } else {
        if (curRes?.['/purchaseApplyController/addApply']) {
          return true;
        }
      }
    }

    if (currentStep == 1) {
      if (applyInfo?.id) {
        if (applyInfo?.state == QC_SQSTATE() && !applyInfo?.checkState && curRes?.['/purchasePackController/editPack']) {
          return true;
        }
        if (
          applyInfo?.state == SHZ_SQSTATE() &&
          applyInfo?.checkState == SHTH_CHECKSTATE() &&
          applyInfo?.applyerID == getUserID() &&
          applyInfo?.applyPositionID == getPosIDs() &&
          curRes?.['/purchasePackController/editPack']
        ) {
          return true;
        }
      } else {
        if (curRes?.['/purchasePackController/addPack'] && applyInfo?.id) {
          return true;
        }
      }
    }
    return false;
  }, [curRes, applyInfo, currentStep, finallyType]);

  return (
    <ApplyUpdateContext.Provider
      value={{
        prefixCls,
        materialList,
        applyInfo,
        ProjectInfo,
        supplyWay,
        curRes,
        dispatch,
        locationProps: locationProps?.state,
        successMaterials,
        setSuccessMaterials,
        finallyType,
        reloadInfoService,
        page_s: page,
        packData,
        setPackData,
        type,
        dataSource,
        isShowSubmit,
      }}
    >
      <div className={prefixCls}>
        {
          <div className={`${prefixCls}-steps`}>
            <Steps size="small" current={currentStep} items={stepsItems} onChange={(current) => setCurrentStep(current)} />
          </div>
        }
        <>
          <div style={{ height: '100%', overflow: 'hidden', background: '#fff' }}>
            <Spin spinning={loading}>
              <ScrollBarLayout style={{ padding: 12 }}>
                {/* 基本信息 */}
                <div className={currentStep == 0 ? '' : 'apply-threeCptdisplayNone'}>
                  <UpdateStepsBaseInfo ref={ref.stepsBaseInfoRef} />
                </div>
                {/* 标包信息 */}
                <div className={currentStep == 1 ? '' : 'apply-threeCptdisplayNone'}>
                  <UpdateStepsPack onClickSave={submit?.saveApply} ref={ref.stepsPackRef} />
                </div>
                {/* 信息确认 */}
                <div className={currentStep == 2 ? '' : 'apply-threeCptdisplayNone'}>
                  <UpdateStepsApply ref={ref.stepsApplykRef} />
                </div>
              </ScrollBarLayout>
            </Spin>
          </div>
          <div className={`${prefixCls}-footer`}>
            <Space>
              {finallyType != 'view' && (
                <Button onClick={() => changeStep('prev')} onMouseOut={onMouseOut_ANTDBTN} type="primary" disabled={!(currentStep != 0)}>
                  上一步
                </Button>
              )}

              {isShowSubmit && (
                <Button loading={loading} type="primary" onClick={() => submit.saveApply()}>
                  暂存
                </Button>
              )}

              {currentStep == 2 &&
                applyInfo.state == QC_SQSTATE() &&
                applyInfo.checkState == null &&
                curRes?.['/purchaseApplyController/startProcess/{starterDeptID}'] &&
                inspectChangeState && (
                  <Button
                    type="primary"
                    // icon={<SendOutlined />}
                    onClick={submit.submitApply}
                    loading={loading}
                  >
                    提交
                  </Button>
                )}

              {currentStep == 2 && inspectChangeState && applyInfo?.state == SHZ_SQSTATE() && (
                <WorkflowHndTaskBtn
                  flowDetailInfo={applyInfo}
                  flowBusinessType={SQ_flowBusinessType()}
                  requestController={SQ_requestController()}
                  reloadCallback={reloadInfoService}
                  isAloneSubmit={applyInfo?.state == SHZ_SQSTATE() && applyInfo.checkState == SHTH_CHECKSTATE()}
                  applyHeader={'apply'}
                  revokeRequestUrl={'/purchaseApplyController/invalid'}
                  revokeRequestState={`${getTenantID()}${ILoadMapTypeAll?.PURAPPLY_STATE}`}
                  isShowRevokeStateList={[SHZ_SQSTATE()]}
                  revokeTitle={applyInfo?.applyTitle}
                  revokeSuccessCallback={() => {
                    history.push({
                      pathname: `/purchaseApplyController/editApply/:${getKeyRouter()}${getKeyRouter()}`,
                      state: {
                        type: 'edit',
                        info: applyInfo,
                        source: 'apply',
                        returnPathName: returnPathName,
                        delRouterName: history.location.pathname,
                      },
                    });
                  }}
                />
              )}

              {returnPathName && (
                <Button danger onClick={() => closeCurrent(returnPathName)}>
                  关闭
                </Button>
              )}

              {/* {curRes['/purchaseApplyController/invalid'] &&
                applyInfo?.id &&
                applyInfo?.applyerID == getUserID() &&
                applyInfo?.applyPositionID == getPosIDs() &&
                applyInfo?.applyPositionID == getPosIDs() &&
                applyInfo?.state == SHZ_SQSTATE() &&
                currentStep == 2 && (
                  <Button
                    type="primary"
                    danger
                    // icon={<RollbackOutlined />}
                    onClick={() => {
                      setInvalidState({ isShow: true, resObj: applyInfo });
                    }}
                  >
                    撤销
                  </Button>
                )} */}

              {/* applyInfo?.state && currentStep != stepsItems.length - 1 && isShowSubmit &&  */}
              {finallyType != 'view' && (
                <Button type="primary" onClick={() => changeStep('next')} onMouseOut={onMouseOut_ANTDBTN} disabled={!(currentStep != 2)}>
                  下一步
                  {/* <ArrowRightOutlined /> */}
                </Button>
              )}
            </Space>
          </div>
        </>

        {/* {invalidState?.isShow && (
          <RevokeModal
            resObj={invalidState?.resObj}
            revokeRequestUrl={'/purchaseApplyController/invalid'}
            onClose={() => setInvalidState({})}
            reqBody={{ state: QC_SQSTATE() }}
            modalTip={
              <div style={{ color: '#000' }}>
                确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.applyTitle}</span>】的审核, 撤销后可重新提交！
              </div>
            }
            reloadRequest={() => {
              history.push({
                pathname: `/purchaseApplyController/editApply/:${getKeyRouter()}${getKeyRouter()}`,
                state: {
                  type: 'edit',
                  info: invalidState?.resObj,
                  source: 'apply',
                },
              });
            }}
          />
        )} */}

        {/* 审核记录 */}
        {applyInfo?.paramObject?.[SQ_flowBusinessType()] && (
          <div style={{}}>
            <WorkflowChedkRecord
              curRes={curRes}
              dataDetailInfo={applyInfo}
              flowBusinessType={SQ_flowBusinessType()}
              requestController={SQ_requestController()}
              reloadPageCallback={reloadInfoService} // 刷新方法-详情方法
              revokeStateID={QC_SQSTATE()}
              allBtnFuncQuqry={isShowState?.workflowPowerAllBtn}
              tabPaneHeight={0.35}
              isCheckDrawer={true}
              isShowCollapse={isShowAuditRecord}
              changeCollapse={(val) => setIsShowAuditRecord(val)}
              cancelStateId={`${getTenantID()}${ILoadMapTypeAll.PURAPPLY_STATE}1007`}
              isSyncArchive={true}
            />
          </div>
        )}
      </div>

      {/* 发起流程审批 */}
      {isShowState.workFlowInfoObj?.showWorkFlowModal && (
        <WorkflowSwitchModal
          openVisible={isShowState.workFlowInfoObj?.showWorkFlowModal}
          businessInfoObj={{
            ...applyInfo,
            // ...isShowState.workFlowInfoObj?.selectFlowRows,
            // relateDepartmentID: applyInfo?.supplyWay == 1 ? applyInfo?.unitDepartmentID : null,
            // busiDepartmentID: applyInfo?.supplyWay == 1 ? applyInfo?.busiDepartmentID : null,
          }}
          requestController={SQ_requestController()}
          orderType={isShowState.workFlowInfoObj?.selectFlowRows?.orderType || SQ_orderType()}
          category={SQ_flowBusinessType()}
          // businessCategory={applyInfo?.supplyWay == 0 ? SQ_businessCategory() : SQ_LX_businessCategory()}
          businessCategory={SQ_businessCategory()} // 统一使用 "月度计划" 的流程
          reloadInfoCallback={() => {
            // reloadInfoService
            // 跳转详情页面
            history.push({
              pathname: `/purchaseApplyController/getApplyDetails/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
              state: {
                type: 'view',
                info: applyInfo,
                source: 'apply',
                step: 0,
                returnPathName: returnPathName,
                delRouterName: history.location.pathname,
              },
            });
          }}
          openFlowChangeModal={change.setShowSwitchFlow}
          selectFlowID={isShowState.workFlowInfoObj?.saveNoDefaultFlowID}
          onClose={() => {
            change.onChangeWorkFlowInfoObj({
              ...isShowState.workFlowInfoObj,
              showWorkFlowModal: false,
            });
          }}
          replaceStrObj={{ own: 'apply', workflowType: 'category' }}
          // workFlowName={applyInfo?.supplyWay == 0 ? '月度计划采购申请审批流程_调整' : applyInfo?.supplyWay == 1 ? '零星采购申请审批流程_调整' : undefined}
          workFlowName={applyInfo?.purchCategory == 2 ? '职能部门月度计划采购申请审批流程_调整' : '科研团队月度计划采购申请审批流程_调整'}
        />
      )}

      {/* 挑选流程组件 */}
      {isShowState.showSwitchFlow && (
        <WorkflowNoDefaultTable
          openVisibleSwitch={isShowState.showSwitchFlow}
          onCloseSwitch={change.closeSwitchFlowModal}
          requestController={SQ_requestController()}
          orderType={isShowState.workFlowInfoObj?.selectFlowRows?.orderType || SQ_orderType()}
          category={SQ_flowBusinessType()}
          // businessCategory={applyInfo?.supplyWay == 0 ? SQ_businessCategory() : SQ_LX_businessCategory()}
          businessCategory={SQ_businessCategory()} // 统一使用 "月度计划" 的流程
          saveSelectFlowID={(flowId: string) => {
            change.onChangeWorkFlowInfoObj({
              ...isShowState.workFlowInfoObj,
              saveNoDefaultFlowID: flowId,
            });
          }}
          selectFlowID={isShowState.workFlowInfoObj?.saveNoDefaultFlowID}
        />
      )}

      {/* 流程办理弹窗 */}
      {isShowWorkflowCheck?.isShow && (
        <WorkflowCheckModal
          detailInfoObj={applyInfo?.paramObject?.[SQ_flowBusinessType()]?.mactivitiTaskList?.[0]}
          flowBusinessType={SQ_flowBusinessType()}
          requestController={SQ_requestController()}
          clickBtnText={isShowWorkflowCheck?.resObj}
          reloadCallback={() => {
            reloadInfoService();
          }}
          onClose={() => setIsShowWorkflowCheck({})}
        />
      )}
    </ApplyUpdateContext.Provider>
  );
};
export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(ApplyUpdateView);
